using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;

namespace PS.WebParts.Rollup
{
    public abstract class ATabularDataSourceView : DataSourceView
    {
        protected StringBuilder _processingMessages;
        private Object cachedReturnType;
        private DataSourceCollection cachedDataSources;
        private ExecutionStats stats;

        public void ForceRollupRerun()
        {
            cachedReturnType = null;
        }

        internal DataSourceCollection CachedDataSources
        {
            get { return cachedDataSources; }
        }

        protected void SetCachedDataSources(DataSourceCollection data)
        {
            cachedDataSources = data;
        }

        public string ProcessingMessages
        {
            get { return _processingMessages != null ? _processingMessages.ToString() : null; }
        }

        protected internal void LogError(string message)
        {
            LogError(message, null);
        }

        protected internal void LogError(string message, Exception exception)
        {
            if (_processingMessages == null)
                _processingMessages = new StringBuilder();

            _processingMessages.AppendFormat("Exception: {0}\n{1}\n\n", message,
                                             exception != null ? exception.ToString() : null);
        }

        public abstract DataTable GetData();

        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)
        {
            stats = new ExecutionStats();
            DataTable res = cachedReturnType as DataTable;

            stats.SetQueryBegin();
            if (res == null)
            {
                res = GetData();
                cachedReturnType = res;
            }

            stats.SetQueryEnd();

            //return res != null ? new DataView(res) : null;
            return res != null ? res.DefaultView : null;
        }

        private HttpContext context;

        protected HttpContext Context
        {
            get { return context; }
        }

        public ExecutionStats Stats
        {
            get
            {
                if (stats == null)
                {
                    stats = new ExecutionStats();
                }
                return stats;
            }
        }

        protected ATabularDataSourceView(HttpContext context, IDataSource owner, string viewName)
            : base(owner, viewName)
        {
            this.context = context;
        }

        /// <summary>
        /// Returns an empty datatable based on columns defined in the ListFields and IncludeListData attributes
        /// </summary>
        /// <returns></returns>
        public abstract DataTable GetSchema();
    }
}